import type { CurrencyCode, CurrencyInfo, CurrencyState } from '@/types/pinia'

// 币种配置
export const CURRENCIES: Record<CurrencyCode, CurrencyInfo> = {
	CNY: {
		code: 'CNY',
		symbol: '¥',
		name: '人民币',
		rate: 1.0
	},
	USD: {
		code: 'USD',
		symbol: '$',
		name: '美元',
		rate: 0.14
	},
	RUB: {
		code: 'RUB',
		symbol: '₽',
		name: '卢布',
		rate: 10.0
	}
} as const

export const useCurrencyStore = defineStore('currency', {
	state: (): CurrencyState => ({
		currentCurrency: 'CNY'
	}),

	getters: {
		getCurrentCurrency: state => state.currentCurrency,
		getCurrentCurrencyInfo: state => CURRENCIES[state.currentCurrency],
		getCurrencies: () => Object.values(CURRENCIES),

		// 格式化金额
		formatAmount: state => (amount: number) => {
			const currency = CURRENCIES[state.currentCurrency]
			const convertedAmount = amount * currency.rate
			return `${currency.symbol}${convertedAmount.toFixed(2)}`
		},

		// 获取汇率
		getExchangeRate: state => (targetCurrency: CurrencyCode) => {
			const currentRate = CURRENCIES[state.currentCurrency].rate
			const targetRate = CURRENCIES[targetCurrency].rate
			return targetRate / currentRate
		}
	},

	actions: {
		setCurrency(currency: CurrencyCode) {
			this.currentCurrency = currency
		},

		// 转换金额到指定币种
		convertAmount(amount: number, targetCurrency: CurrencyCode): number {
			const currentRate = CURRENCIES[this.currentCurrency].rate
			const targetRate = CURRENCIES[targetCurrency].rate
			return amount * (targetRate / currentRate)
		}
	}
})
